package com.gxa.user.recycling.service.impl;

import com.gxa.core.recycling.common.ExceptionCode;
import com.gxa.core.recycling.exception.BusinessException;
import com.gxa.core.recycling.pojo.Goods;
import com.gxa.core.recycling.pojo.Imgs;
import com.gxa.core.recycling.service.impl.BaseServiceImpl;
import com.gxa.user.recycling.repository.GoodsRepository;
import com.gxa.user.recycling.repository.ImagesRepository;
import com.gxa.user.recycling.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("goodsService")
@Transactional(rollbackFor = {Throwable.class})
public class GoodsServiceImpl extends BaseServiceImpl<Goods> implements GoodsService {
    @Autowired
    GoodsRepository goodsRepository;

    @Autowired
    ImagesRepository imagesRepository;
    @Override
    public Goods selectById(Long id) throws BusinessException {
        Goods goods = goodsRepository.findGoodsByIdEquals(id);
        if(goods==null){
            throw new BusinessException(ExceptionCode.NOFIND_GOODS);
        }
        return goods;
    }

    @Override
    public List<Map<String, Object>> findGoodsByHotAndState(Boolean hot, Boolean state) {
        ArrayList<Map<String,Object>> objects = new ArrayList<>();
        List<Goods> goodsByHotAndState = goodsRepository.findGoodsByHotAndState(true, true);
        for (int i = 0; i < goodsByHotAndState.size(); i++) {
            Goods goods = goodsByHotAndState.get(i);
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("goods",goods);
            List<Imgs> imgsByGidEquals = imagesRepository.findImgsByGidEquals(goods.getId());
            hashMap.put("imgs",imgsByGidEquals);
            objects.add(hashMap);
        }
        return objects;
    }
}
